const mysql = require('mysql')
//数据库配置
const config = {
	host: 'localhost',
	port: '3306',
	user: 'root',
		password: 'root',
		database: 'easttown'
	}
	
	const pool = mysql.createPool(config)

	//链接数据库,使用连接池的方式
	//连接池的对象
	const sqlConnect = function (sql, values, callBack) {
		pool.getConnection((err, conn) => {
			if (err) {
				console.log("sqlConnect连接失败")
				return
			}
			//事件驱动回调
			conn.query(sql, values, callBack)
			//释放连接
			conn.release()
		})
	}
	
	//promise回调
	const SySqlConnect = (sql, values=[]) => {
		return new Promise((resolve, reject) => {
			pool.getConnection((err, connection) => {
				if (err) {
					reject(err);
					return;
				}
				connection.query(sql, values, (error, results, fields) => {
					connection.release();
					if (error) {
						reject(error);
						return;
					}
					resolve(results);
				});
			});
		});
	};

module.exports = {
	SySqlConnect,
	sqlConnect
}